<?php
/**
 * Created by PhpStorm.
 * User: 王 朋
 * Date: 2018/4/10
 * Time: 23:06
 */
namespace application\teacher\controller;
use application\common\controller\Base;
use think\Db;
use think\exception\HttpException;
use think\Session;
use PHPExcel\IOFactory;
use application\common\model\ExamineeInfo;
use application\common\model\Notify;
use application\common\controller\Tools;
use cauliflower\Library\Exception\UploadFileException;
use cauliflower\Library\Exception\SaveDataException;
use cauliflower\Library\File\Download;
use cauliflower\Library\File\CompressFile;
use application\common\model\SystemConfig;
use application\common\controller\Util;

class Exam extends Base
{
    public function addExam() {
        if (! $this->request->isPost()) {
            $this->assign([
                'title' => '添加考试',
                'messageCount' => 0,
            ]);
            return $this->fetch();
        }else {
            $exam = new \application\common\model\Exam();
            $examName = $this->request->post('examName');
            $startTime = $this->request->post('startTime');
            $examDuration = $this->request->post('examDuration');
            $isAutoStart = $this->request->post('isAutoStart');
            $attention = $this->request->post('attention');
            if (empty($examName) || empty($startTime) || empty($examDuration) || empty($isAutoStart) || empty($attention) ) {
                $this->error('请确认考试信息是否填写完整！',$_SERVER['HTTP_REFERER']);
            } else if (mb_strlen($examName) > 20) {
                $this->error('考试名称应在20个字以内！', $_SERVER['HTTP_REFERER']);
            } else if (mb_strlen($attention) > 100) {
                $this->error('注意事项应在100字以内！', $_SERVER['HTTP_REFERER']);
            } else if (!Util::str_is_int($examDuration) || !in_array($isAutoStart, array('yes', 'no'))) {
                $this->error('参数非法！', $_SERVER['HTTP_REFERER']);
            } else {
                $reExam = $exam->where('exam_name',$examName)->where('exam_creator_id',Session::get('userId'))->find();
                if ($reExam) {
                    $this->error('已经存在该考试！',$_SERVER['HTTP_REFERER']);
                }
                $data = [
                    'exam_name' => Util::filter_str($examName),
                    'exam_startTime' => $startTime,
                    'exam_duration' => $examDuration,
                    'exam_creator_id' => Session::get('userId'),
                    'exam_autoStart' => $isAutoStart=='yes' ? 1 : 0,
                    'attention_matters' => Util::filter_str($attention),
                ];
                $exam->data($data)->save();
                if ($isAutoStart === 'yes') {
                    $examID = $exam->getLastInsID();
                    $this->autoStartExam(strtotime($startTime), $examID, ((int)$examDuration) * 60);
                }
                $this->redirect('index/index');
            }
        }
    }
    public function deleteExam() {
        $exams = input('post.items/a');
        if (! $exams) {
            $this->error("您未选择要删除的考试。",'index/index');
        }
        $data = [];
        foreach ($exams as $item) {
            $data = [
                'exam_name' => $item,
                'exam_creator_id' => Session::get('userId'),
            ];
            \application\common\model\Exam::destroy($data);
        }
        $this->redirect('index/index');
    }
    public function deleteOneExam() {
        \application\common\model\Exam::destroy(['exam_name' => Session::get('examName'), 'exam_creator_id' => Session::get('userId')]);
        $this->redirect('index/index');
    }
    public function examineeInfo($examName) {
        //$sql = 'select * from cfe_examinee_info where exam_id=(select exam_id from cfe_exam where exam_name=? and exam_creator_id=?)';
        //$examinee = Db::query($sql,[$examName,Session::get("userId")]);
        $exam = new \application\common\model\Exam();
        $examInfo = $exam->where('exam_name',$examName)->where('exam_creator_id',Session::get('userId'))->select()[0];
        $paperPath = $examInfo['paper_realName'];
        $examn = new ExamineeInfo();
        $examinee = $examn->where('exam_id', $examInfo['exam_id'])->paginate(Session::get('pageNum'));
        $this->assign([
            'title' => '考生信息',
            'messageCount' => 0,
            'examName' => $examName,
            'alert' => $examinee->total() ? 'hidden' : 'show',
            'table' => $examinee->total() ? '' : 'none',
            'examinees' => $examinee,
            'button' => $examinee->total() ? 'block' : 'none',
            'paperAlert' => $paperPath ? 'hidden' : 'show',
            'paperDiv' => $paperPath ? 'show' : 'hidden',
            'paperPath' => $paperPath,
        ]);
        Session::set('examName',$examName);
        return $this->fetch();
    }
    public function batchLiExaminee() {
        if (! $this->request->isPost()) {
            throw new HttpException('403');
        }else {
            if (! $this->request->file('examinee')) {
                $this->error("请确认您选择的文件！",$_SERVER['HTTP_REFERER']);
            }
            $excel = $this->request->file('examinee')->getInfo();
            if ($this->request->has('examName','post')) {
                $examName = $this->request->post('examName');
            }else {
                throw new HttpException('403');
            }
            $etx = strstr($excel['name'],'.');
            if ( $etx != '.xls' && $etx != '.xlsx') {
                $this->error("导入文件格式必须是Excel文件！",'examineeInfo?examName='.$examName);
            }
            $objPHPExcel = IOFactory::load($excel['tmp_name']);
            $arrExcel = $objPHPExcel->getSheet(0)->toArray();
            $exam = new \application\common\model\Exam();
            $examId = $exam->where('exam_creator_id',Session::get('userId'))->where('exam_name',$examName)->column('exam_id')[0];
            $examineeInfo = new ExamineeInfo();
            $data = [];
            if (next($arrExcel)) {
                for ($i = 1; $i < count($arrExcel); $i++) {
//                    $data[] = [
//                        'exam_id' => $examId,
//                        'studentID' => $arrExcel[$i][0],
//                        'studentName' => $arrExcel[$i][1],
//                        'uniqueID' => Tools::md5Uniqid(),
//                    ];
                    $sql = 'INSERT INTO cfe_examinee_info (exam_id, studentID, studentName, uniqueID) SELECT ?, ?, ?, ? FROM DUAL WHERE NOT EXISTS (SELECT exam_id, studentID FROM cfe_examinee_info WHERE exam_id = ? AND studentID = ?)';
                    Db::execute($sql, array($examId, $arrExcel[$i][0], $arrExcel[$i][1], Tools::md5Uniqid(), $examId, $arrExcel[$i][0]));
                }
                $this->redirect($_SERVER['HTTP_REFERER']);
//                if ($examineeInfo->saveAll($data)) {
//                    $this->redirect($_SERVER['HTTP_REFERER']);
//                }else {
//                    $this->error("导入考生信息失败！","index/index");
//                }
            }else {
                $this->error("您导入的文件中没有考生信息！","index/index");
            }
        }
    }
    public function uploadExampaper() {
        if (! $this->request->isPost()) {
            throw new HttpException('403');
        }else {
            $paper = $this->request->file('paper');
            if (! $paper) {
                $this->error("请确认您选择的文件！",$_SERVER['HTTP_REFERER']);
            }else {
                $fileName = $paper->getInfo('name');
                if (strrchr($fileName, ".") == ".php") {
                    $this->error('导入文件非法！', $_SERVER['HTTP_REFERER']);
                }
                $md5Name = Tools::md5Uniqid();
                $exam = new \application\common\model\Exam();
                $realName = $exam->where('exam_name',Session::get('examName'))
                            ->where('exam_creator_id',Session::get('userId'))
                            ->column('paper_realName')[0];
                //无论是否抛出异常，在正常执行恢复之前，finally块中的代码将始终在try和catch块后执行。
                try {
                    if (! is_dir(ROOT_PATH.'uploads')) {
                        mkdir(ROOT_PATH.'uploads');
                    }
                    if (! is_dir(ROOT_PATH.'uploads'.DS.'paper')) {
                        mkdir(ROOT_PATH.'uploads'.DS.'paper');
                    }
                    if (! is_dir(ROOT_PATH.'uploads'.DS.'paper'.DS.Session::get('examName'))) {
                        mkdir(ROOT_PATH.'uploads'.DS.'paper'.DS.Session::get('examName'));
                    }
                    $info = $paper->move(ROOT_PATH.'uploads'.DS.'paper'.DS.Session::get('examName'),$paper->getInfo('name'));
                    if (! $info) { // 上传失败
                        throw new UploadFileException();
                    }else {
                        // 只有unset掉$info才能删除刚上传的文件
                        unset($info);
                        $result = $exam->save([
//                            'paper_phoneyName' => $md5Name.strstr($fileName,'.'),
                            'paper_realName' => $paper->getInfo('name'),
                        ],[
                            'exam_name' => Session::get('examName'),
                            'exam_creator_id' => Session::get('userId'),
                        ]);
                        if (! $result && $paper->getInfo('name') != $realName) { // 存入数据库失败，上传成功的文件名和原先的文件名不一致时的处理情况
                            throw new SaveDataException();
                        }else {
                            // 一切正常，旧文件与上传文件名不一致并且真的存在旧文件时的处理情况
                            if ($result && $paper->getInfo('name') != $realName && is_file(ROOT_PATH.'uploads'.DS.'paper'.DS.Session::get('examName').DS.$realName)) {
                                unlink(ROOT_PATH.'uploads'.DS.'paper'.DS.Session::get('examName').DS.$realName);
                            }
                        }
                    }
                }catch (UploadFileException $e) {
                    $this->error("上传试卷失败！",'index/index');
                }catch (SaveDataException $e) {
                    $filePath = ROOT_PATH.'uploads'.DS.'paper'.DS.Session::get('examName').DS.$paper->getInfo('name');
                    if (is_file($filePath)) {
                        unlink($filePath);
                    }
                    $this->error("操作失败！",'index/index');
                }catch (\Exception $e) {
                    $this->error('发生未知错误！','index/index');
                }
                $this->redirect('examineeInfo?examName='.Session::get('examName'));
            }
        }
    }
    public function downloadExampaper($fileName) {
        $filePath = ROOT_PATH.'uploads'.DS.'paper'.DS.Session::get('examName').DS.$fileName;
        if (! Download::downloadFile($filePath,$fileName)) {
            return "<script>alert('下载失败！')</script>";
        }
    }
    public function examManager($examName) {
        $exam = new \application\common\model\Exam();
        $examInfo = $exam->where('exam_name',$examName)->where('exam_creator_id',Session::get('userId'))->select()[0];
        $examinee = new ExamineeInfo();
        $totalNum = $examinee->where('exam_id', $examInfo['exam_id'])->count();
        $loginNum = $examinee->where('exam_id', $examInfo['exam_id'])->where('studentBindIP', '<>', '0.0.0.0')->count();
        $submitNum = $examinee->where('exam_id', $examInfo['exam_id'])->where('answerPath', '<>', '')->count();
        $this->assign([
            'title' => '添加考试',
            'messageCount' => 0,
            'exam' => $examInfo,
            'examName' => $examName,
            'total' => $totalNum,
            'login' => $loginNum,
            'not_login' => $totalNum - $loginNum,
            'submit' => $submitNum,
            'not_submit' => $loginNum - $submitNum,
            'content' => $examInfo['status'] === '3' ? 'hidden' : 'show',
            'cleanAlert' => $examInfo['status'] === '3' ? 'show' : 'hidden',
        ]);
        Session::set('examName', $examName);
        return $this->fetch();
    }
    public function startExam($examName) {
        $exam = new \application\common\model\Exam();
        $config = new SystemConfig();
        $examInfo = $exam->where('exam_name',$examName)->where('exam_creator_id',Session::get('userId'))->select()[0];
        $configInfo = $config->where('system_id',1)->select()[0];
        $startTimestamp = strtotime($examInfo['exam_startTime']);
        $timeDifference = abs(time() - $startTimestamp);
        if ($timeDifference / 60 > $configInfo['startThreshold']) {
            $this->error("目前不在开始该考试的时间范围内！",$_SERVER['HTTP_REFERER']);
        }else {
            $examID = $examInfo['exam_id'];
            $stopTime = time() + (int)($examInfo['exam_duration']) * 60;
            $this->autoStopExam($stopTime, $examID);
        }
        $exam->save([
            'status' => 1,
        ],[
            'exam_name' => $examName,
            'exam_creator_id' => Session::get('userId'),
        ]);
        $this->redirect("examManager?examName=$examName");
    }
    public function modifyExam($oldExamName) {
        if (! $this->request->isPost()) {
            throw new HttpException('403');
        }else {
            $exam = new \application\common\model\Exam();
            $examName = $this->request->post('examName');
            $startTime = $this->request->post('startTime');
            $examDuration = $this->request->post('examDuration');
            $isAutoStart = $this->request->post('isAutoStart');
            $attention = $this->request->post('attention');
            if (empty($examName) || empty($startTime) || empty($examDuration) || empty($isAutoStart) || empty($attention)) {
                throw new HttpException('406');
            } else {
                $reExam = $exam->where('exam_name',$examName)->where('exam_creator_id',Session::get('userId'))->find();
                // 新考试名称和旧考试名称不同，且已存在以新名称命名的考试时不允许修改
                if ($oldExamName != $examName && $reExam) {
                    $this->error('考试名不可重复！',$_SERVER['HTTP_REFERER']);
                }
                $exam->save([
                    'exam_name' => Util::filter_str($examName),
                    'exam_startTime' => $startTime,
                    'exam_duration' => $examDuration,
                    'exam_creator_id' => Session::get('userId'),
                    'exam_autoStart' => $isAutoStart == 'yes' ? 1 : 0,
                    'attention_matters' => Util::filter_str($attention),
                ], ['exam_name' => $oldExamName, 'exam_creator_id' => Session::get('userId')]);
                $this->redirect('index/index');
            }
        }
    }
    public function stopExam($examName) {
        $exam = new \application\common\model\Exam();
        $exam->save([
            'status' => 2,
        ],[
            'exam_name' => $examName,
            'exam_creator_id' => Session::get('userId'),
        ]);
        $this->redirect("examManager?examName=$examName");
    }
    public function autoStartExam($startTime, $examID, $duration) {
        $url = 'http://'.$_SERVER['HTTP_HOST'].'/cauliflowerExam/script/application/teacher/AutoStartExam.php?runTime='.$startTime.'&examID='.$examID.'&duration='.$duration;
        $err = Tools::_sock($url);
        if ($err['err_code'] === 0) {
            return true;
        }else {
            return false;
        }
    }
    public function autoStopExam($stopTime, $examID) {
        $url = 'http://'.$_SERVER['HTTP_HOST'].'/cauliflowerExam/script/application/teacher/AutoStopExam.php?runTime='.$stopTime.'&examID='.$examID;
        $err = Tools::_sock($url);
        if ($err['err_code'] === 0) {
            return true;
        }else {
            return false;
        }
    }
    public function showLogin($examName) {
        $exam = new \application\common\model\Exam();
        $examinee = new ExamineeInfo();
        $examId = $exam->where(['exam_name' => $examName, 'exam_creator_id' => Session::get('userId')])->column('exam_id')[0];
        $login = $examinee->where('exam_id', $examId)->where('studentBindIP', '<>', '0.0.0.0')->select();
        $not_login = $examinee->where('exam_id', $examId)->where('studentBindIP', '0.0.0.0')->select();
        $this->assign([
            'title' => '学生登录信息',
            'messageCount' => 0,
            'login' => $login,
            'not_login' => $not_login,
        ]);
        return $this->fetch();
    }
    public function showSubmit($examName) {
        $exam = new \application\common\model\Exam();
        $examinee = new ExamineeInfo();
        $examId = $exam->where(['exam_name' => $examName, 'exam_creator_id' => Session::get('userId')])->column('exam_id')[0];
        $submit = $examinee->where('exam_id', $examId)->where('studentBindIP', '<>', '0.0.0.0')->where('answerPath', '<>', '')->select();
        $not_submit = $examinee->where('exam_id', $examId)->where('studentBindIP', '<>', '0.0.0.0')->where('answerPath', '')->select();
        $this->assign([
            'title' => '学生提交信息',
            'messageCount' => 0,
            'submit' => $submit,
            'not_submit' => $not_submit,
        ]);
        return $this->fetch();
    }
    public function search() {
        if(! $this->request->isPost()) {
            throw new HttpException('403');
        }else {
            $examName = $this->request->post('examName');
            $type = $this->request->post('type');
            $key = $this->request->post('key');
            if (empty($examName) || empty($type) || empty($key)) {
                throw new HttpException('406');
            }else {
                // 对于通过考号和姓名的查询只提供精准查询
                $exam = new \application\common\model\Exam();
                $examinee = new ExamineeInfo();
                $examId = $exam->where(['exam_name' => $examName, 'exam_creator_id' => Session::get('userId')])->column('exam_id')[0];
                $first = $examinee->where('exam_id', $examId);
                if ($type == 'id') {
                    $examinees = $first->where('studentID', 'LIKE','%'.$key.'%')->select();
                }elseif($type == 'name') {
                    $examinees = $first->where('studentName', 'LIKE','%'.$key.'%')->select();
                }else {
                    $examinees = $first->where('studentBindIP', 'LIKE','%'.$key.'%')->select();
                }
                $this->assign([
                    'title' => '搜索考生',
                    'messageCount' => 0,
                    'alert' => $examinees ? 'hidden' : 'show',
                    'examinees' => $examinees,
                    'result' => $examinees ? 'show' : 'hidden',
                    'examName' => $examName,
                ]);
                return $this->fetch();
            }
        }
    }
    public function bindIP($who, $examName) {
        $examinee = new ExamineeInfo();
        $examineeInfo = $examinee->where('id', $who)->select()[0];
        if ($examineeInfo['studentBindIP'] == '0.0.0.0') {
            $this->error("该考生还未登录，请先登录！", url('examineeInfo?examName='.$examName));
        }else {
            $examinee->save(['isLockingIP' => '1'],['id' => $who]);
        }
        $this->redirect('examineeInfo?examName='.$examName);
    }
    public function untieIP($who, $examName) {
        $examinee = new ExamineeInfo();
        $examineeInfo = $examinee->where('id', $who)->select()[0];
        if ($examineeInfo['studentBindIP'] == '0.0.0.0') {
            $this->error("该考生还未登录，请先登录！", url('examineeInfo?examName='.$examName));
        }else {
            $examinee->save(['isLockingIP' => '0'],['id' => $who]);
        }
        $this->redirect('examineeInfo?examName='.$examName);
    }
    public function notify() {
        $exam = new \application\common\model\Exam();
        $examId = $exam->where(['exam_name' => Session::get('examName'), 'exam_creator_id' => Session::get('userId')])->column('exam_id')[0];
        if (! $examId) {
            $this->error('未知错误！', $_SERVER['HTTP_REFERER']);
        }
        $notify = new Notify();
        $notifys = $notify->where('exam_id', $examId)->select();
        $this->assign([
            'title' => '通知',
            'messageCount' => 0,
            'alert' => $notifys ? 'hidden' : 'show',
            'showNotify' => $notifys ? 'show' : 'hidden',
            'notifys' => $notifys,
        ]);
        return $this->fetch();
    }
    public function addNotify() {
        if (! $this->request->isPost()) {
            $this->assign([
                'title' => '添加通知',
                'messageCount' => 0,
            ]);
            return $this->fetch();
        }else {
            $title = $this->request->post('title');
            $content = $this->request->post('content');
            if (empty($title) || empty($content)) {
                $this->error('请确认通知信息是否填完整！', $_SERVER['HTTP_REFERER']);
            }
            if (mb_strlen($title) > 20) {
                $this->error('标题过长，标题应在20字以内！', $_SERVER['HTTP_REFERER']);
            }
            if (mb_strlen($content) > 300) {
                $this->error('内容过长，内容应在300字以内！', $_SERVER['HTTP_REFERER']);
            }
            $exam = new \application\common\model\Exam();
            $examId = $exam->where(['exam_name' => Session::get('examName'), 'exam_creator_id' => Session::get('userId')])->column('exam_id')[0];
            if (! $examId) {
                $this->error('未知错误！', $_SERVER['HTTP_REFERER']);
            }
            $notify = new Notify();
            $notify->save(['exam_id' => $examId, 'notify_title' => Util::filter_str($title), 'notify_message' => Util::filter_str($content), 'notify_time' => date('Y-m-d H:i:s', time())]);
            $this->redirect('notify');
        }
    }
    public function deleteNotify($notify) {
        $id = round(($notify-31242) / 13);
        Notify::destroy(['notify_id' => $id]);
        $this->redirect("notify");
    }
    public function showNotify($notify) {
        $id = round(($notify-31242) / 13);
        $notify = new Notify();
        $notifyInfo = $notify->where('notify_id', $id)->select()[0];
        if (! $notifyInfo) {
            $this->error("系统错误！", $_SERVER['HTTP_REFERER']);
        }
        $this->assign([
            'title' => '通知详情',
            'messageCount' => 0,
            'notify' => $notifyInfo,
        ]);
        return $this->fetch();
    }
    public function xzAnswer() {
        $compress = new CompressFile();
        $path = ROOT_PATH.'uploads'.DS.'answer'.DS.Session::get('examName').DS;
        if (! is_dir($path)) {
            $this->error("还没有学生提交试卷！", $_SERVER['HTTP_REFERER']);
        }
        $zipName = ROOT_PATH.'zip'.DS.Session::get('examName').'.zip';
        // 如果压缩文件不存在，就创建压缩文件
        if (! is_file($zipName)) {
            $fp = fopen($zipName, 'w');
            fclose($fp);
        }
        $zip = new \ZipArchive();
        // OVERWRITE选项表示每次压缩时都覆盖原有内容，但是如果没有那个压缩文件的话就会报错，所以事先要创建好压缩文件
        // 也可以使用CREATE选项，此选项表示每次压缩时都是追加，不是覆盖，如果事先压缩文件不存在会自动创建
        if ($zip->open($zipName, \ZipArchive::OVERWRITE) === true) {
            $compress->addFileToZip($path, Session::get('examName'), $zip);
            $zip->close();
        }else {
            $this->error("下载文件失败！", $_SERVER['HTTP_REFERER']);
        }
        // 下载压缩后的文件
        if (! Download::downloadFile($zipName, Session::get('examName').'.zip')) {
            return "<script>alert('下载失败！')</script>";
        }else {
            $exam = new \application\common\model\Exam();
            $exam->save(['isZiped' => '1'], ['exam_name' => Session::get('examName'), 'exam_creator_id' => Session::get('userId')]);
            @unlink($zipName);
        }
    }
    public function exportExaminees($examName) {
        $exam = new \application\common\model\Exam();
        $examId = $exam->where('exam_name', $examName)->where('exam_creator_id', Session::get('userId'))->column('exam_id')[0];
        $examinee = new ExamineeInfo();
        $examinees = $examinee->where('exam_id', $examId)->column(['studentID', 'studentName', 'answerTime']);
        vendor('phpExcel.PHPExcel');
        $objPHPExcel = new \PHPExcel();
        $letter = array('A', 'B', 'C');
        $header = array('考号', '姓名', '提交时间');
        // 设置A这一列单元格格式为文本格式
        $objPHPExcel->getActiveSheet()->getStyle('A')->getNumberFormat()->setFormatCode("@");
        for ($i = 0; $i < count($header); $i++) {
            $objPHPExcel->getActiveSheet()->setCellValue("$letter[$i]1", "$header[$i]");
        }
        $j = 2;
        foreach ($examinees as $item) {
            $k = 0;
            foreach ($item as $key => $value) {
                $value = $value == null ? '未提交' : $value;
                $objPHPExcel->getActiveSheet()->setCellValue("$letter[$k]$j", "$value");
                $k++;
            }
            $j++;
        }
        $objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel); //设置保存版本格式
        ob_end_clean();
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/download");
        header('Content-Type:application/octet-stream');
        $ua = $_SERVER["HTTP_USER_AGENT"];
        if (preg_match("/MSIE/", $ua)) {
            header('Content-Disposition: attachment; filename="考生信息.xls"');
        } else if (preg_match("/Firefox/", $ua)) {
            header('Content-Disposition: attachment; filename*="utf8\'\'考生信息.xls"');
        } else {
            header('Content-Disposition: attachment; filename="考生信息.xls"');
        }
        header("Content-Transfer-Encoding:binary");
        $objWriter->save('php://output');
    }
    public function removeDir($dirName) {
        $handle = @opendir($dirName);
        while(($file = @readdir($handle)) !== false) {
            if ($file != '.' && $file != '..') {
                $dir = $dirName.'/'.$file;
                is_dir($dir) ? $this->removeDir($dir) : @unlink($dir);
            }
        }
        closedir($handle);
        return rmdir($dirName);
    }
    public function cleanExam() {
        $config = new SystemConfig();
        $configInfo = $config->where('system_id', '1')->select()[0];
        if ($configInfo['isGrantTeacher'] != '1') {
            $this->error("你没有权限清理考试，如有需要请联系管理员！", $_SERVER['HTTP_REFERER']);
        }
        $exam = new \application\common\model\Exam();
        $examInfo = $exam->where(['exam_name' => Session::get('examName'), 'exam_creator_id' => Session::get('userId')])->select()[0];
        if ($examInfo['isZiped'] != '1') {
            $this->error("打包下载学生提交信息后才能清理考试！", $_SERVER['HTTP_REFERER']);
        }else {
            ExamineeInfo::destroy(['exam_id' => $examInfo['exam_id']]);
            Notify::destroy(['exam_id' => $examInfo['exam_id']]);
            $paperPath = ROOT_PATH.'uploads'.DS.'paper'.DS.Session::get('examName');
            $answerPath = ROOT_PATH.'uploads'.DS.'answer'.DS.Session::get('examName');
            if (is_dir($paperPath)) $this->removeDir($paperPath);
            if (is_dir($answerPath)) $this->removeDir($answerPath);
            $exam->save(['status' => '3'], ['exam_id' => $examInfo['exam_id']]);
            $this->redirect($_SERVER['HTTP_REFERER']);
        }
    }
}